package com.ys.timer;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ys.entity.business.TpAmazonSeller;
import com.ys.entity.business.TpAmazonShop;
import com.ys.entity.business.TsApiLog;
import com.ys.entity.finance.TcwStoreAccount;
import com.ys.enume.AmazonSellerEnum;

import com.ys.mapper.business.DiySqlMapper;
import com.ys.service.finance.TcwFinancesApiDataService;
import com.ys.service.finance.TcwStoreAccountDataService;
import com.ys.service.log.ApiLogService;
import com.ys.util.dhecp.DateUtils;
import com.ys.vo.ApiResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Controller;
import com.ys.enume.finance.TcwStoreAccountEnum;


import java.util.*;


@Controller
public class TimerFinancesApiDataDaily {
	private static Logger logger = LoggerFactory.getLogger(TimerFinancesApiDataDaily.class);

	@Autowired
    private TcwFinancesApiDataService tcwFinancesApiDataService;

	@Autowired
    private TcwStoreAccountDataService tcwStoreAccountDataService;

	@Autowired
	private ApiLogService apiLogService;

	@Autowired
	private DiySqlMapper diySqlMapper;

	public static Map<String, Integer> THREADF_MAP = new HashMap<String, Integer>() {{
		for (int i = 0; i < 15; i++) {
			put("threadAsin" + i, 0);
		}
	}};

	@Scheduled(cron = "0 0 13 1-7 * ?")
	public void getFinancesApi() {
		logger.info("***********每月定时新增财务目录getFinancesApi，开始***********");

		try {
			// 获取星期几
			int dayOfWeek =  Calendar.getInstance().get(Calendar.DAY_OF_WEEK);
			if(dayOfWeek != 1){
				return;
			}

//			上个月第一天
			Calendar calendar = Calendar.getInstance();
			calendar.add(Calendar.MONTH, -1);
			calendar.set(Calendar.DAY_OF_MONTH, calendar.getActualMinimum(Calendar.DAY_OF_MONTH));
			//上个月最后一天
			Calendar calendar1 = Calendar.getInstance();
			calendar1.add(Calendar.MONTH, -1);
			calendar1.set(Calendar.DAY_OF_MONTH, calendar1.getActualMaximum(Calendar.DAY_OF_MONTH));

			calendar.set(Calendar.HOUR_OF_DAY,00);
			calendar.set(Calendar.MINUTE,00);
			calendar.set(Calendar.SECOND,00);

			calendar1.set(Calendar.HOUR_OF_DAY,23);
			calendar1.set(Calendar.MINUTE,59);
			calendar1.set(Calendar.SECOND,59);

			Date startTime = calendar.getTime();
			String startTimeStr = DateUtils.convertDateToTDate(startTime);
			Date endTime = calendar1.getTime();
			String endTimeStr = DateUtils.convertDateToTDate(endTime);

			//删除表中数据
			diySqlMapper.deleteFinancesApiData();
			List<Map<String, Object>> tpAmazonSellerList = new TpAmazonSeller()
					.addLeftJoin("TP_AmazonRegion tar on tar.Code = A.regionCode")//平台地区
					.addField("tar.AwsRegion awsRegion,tar.AmazonServiceUrl amazonServiceUrl,tar.code amazonRegionCode")
					.where("A.authorizeState = '已授权'")
					.setStatus(1)
					.queryMap();
			JSONArray jsonArray = JSONArray.parseArray(JSON.toJSONString(tpAmazonSellerList));
			for (int i = 0; i < jsonArray.size(); i++) {
				JSONObject jsonObject = jsonArray.getJSONObject(i);
				boolean variable = true;
				while (variable) {
					for (Map.Entry<String, Integer> e : THREADF_MAP.entrySet()) {
						if (e.getValue() == 1) {
							continue;
						} else if (e.getValue() == 0) {
							THREADF_MAP.put(e.getKey(), 1);
//								 开启线程
							Thread t = new Thread(() -> {
								ApiResponse apiResponse = tcwFinancesApiDataService.getFinancesApi(jsonObject, startTimeStr, endTimeStr);
								if (apiResponse.getCode() == 500) {
									apiLogService.addApiLog("Amazon", "GetFinancesApi", "ECP_API定时获取亚马逊财务事件信息出错，条件queryParams：" + JSON.toJSONString(jsonObject), "店铺:" + jsonObject.get("sellerName").toString(), apiResponse.getCode(), apiResponse.getMessage());
								}
								logger.info("***********每月定时新增财务目录getFinancesApi，结束***********");

								THREADF_MAP.put(e.getKey(), 0);
							});
							t.start();
							Thread.sleep(1000L);
						}
						variable = false;
						break;
					}
				}
			}
		} catch (Exception ex) {
			ex.printStackTrace();
		}
	}

	@Scheduled(cron = "0 30 14 1-7 * ?")
	public void getFinancesInfo() {
		try {
			logger.info("***********每月定时新增财务事件明细getFinancesInfo，开始***********");
			// 获取星期几
			int dayOfWeek =  Calendar.getInstance().get(Calendar.DAY_OF_WEEK);
			if(dayOfWeek != 1){
				return;
			}

			boolean variable = true;
			while (variable) {
				for (Map.Entry<String, Integer> e : THREADF_MAP.entrySet()) {
					if (e.getValue() == 1) {
						Thread.sleep(10000L);
						variable = true;
						break;
					} else {
						variable = false;
					}
				}
			}

			//上个月第一天
			Calendar calendar = Calendar.getInstance();
			calendar.add(Calendar.MONTH, -1);
			calendar.set(Calendar.DAY_OF_MONTH, calendar.getActualMinimum(Calendar.DAY_OF_MONTH));
			//上个月最后一天
			Calendar calendar1 = Calendar.getInstance();
			calendar1.add(Calendar.MONTH, -1);
			calendar1.set(Calendar.DAY_OF_MONTH, calendar1.getActualMaximum(Calendar.DAY_OF_MONTH));
			calendar.set(Calendar.HOUR_OF_DAY,00);
			calendar.set(Calendar.MINUTE,00);
			calendar.set(Calendar.SECOND,00);

			calendar1.set(Calendar.HOUR_OF_DAY,23);
			calendar1.set(Calendar.MINUTE,59);
			calendar1.set(Calendar.SECOND,59);

			Date startTime = calendar.getTime();
			String startTimeStr = DateUtils.convertDateToTDate(startTime);
			Date endTime = calendar1.getTime();
			String endTimeStr = DateUtils.convertDateToTDate(endTime);

			List<TpAmazonSeller> tpAmazonSellerList = new TpAmazonSeller()
					.where("A.authorizeState = '已授权'")
					.setStatus(1)
					.queryList();
			for (TpAmazonSeller tpAmazonSeller : tpAmazonSellerList) {
				ApiResponse apiResponse = tcwFinancesApiDataService.getFinancesInfo(tpAmazonSeller, startTimeStr, endTimeStr);
				if (apiResponse.getCode() == 500) {
					apiLogService.addApiLog("Amazon", "GetFinancesInfo", "ECP_API定时将Api数据转换Info信息出错，条件queryParams：" + JSON.toJSONString(tpAmazonSeller), "店铺:"+tpAmazonSeller.getSellerName(), apiResponse.getCode(), apiResponse.getMessage());
				}
			}
			logger.info("***********每月定时新增财务事件明细getFinancesInfo，结束***********");
		} catch (Exception ex) {
			ex.printStackTrace();
		}
	}

}
